﻿using System;
using System.Collections;
using System.Collections.Generic;
using Kotonoha.Server.Dictionaries;
using System.Linq;

namespace Kotonoha.Server.Dictionaries.JMDict {

    public class JMdict : IWordDictionary {
        readonly Dictionary<string, List<WordEntry>> entries = new Dictionary<string, List<WordEntry>>(2048);
        private int count = 0;

        private readonly WordEntry[] empty_array = new WordEntry[0];
        public IEnumerable<WordEntry> ByWriting(string writing) {
            List<WordEntry> dictionary;
            if (entries.TryGetValue(writing, out dictionary)) {
                return dictionary;
            }
            return empty_array;
        }

        public IEnumerable<WordEntry> ByReading(string reading) {
            foreach(List<WordEntry> entryL in entries.Values) {
                foreach(WordEntry entry in entryL) {
                    foreach(string enRd in entry.Readings) {
                        if (enRd.Equals(reading)) {
                            yield return entry;
                        }
                    }
                }
            }
        }

        public void Add(WordEntry word) {
            foreach (string wr in word.Writings) {
                List<WordEntry> list;
                if (!entries.TryGetValue(wr, out list)) {
                    list = new List<WordEntry>();
                    entries.Add(wr, list);
                }
                list.Add(word);
                ++count;
            }
        }

        public IEnumerator<WordEntry> GetEnumerator() {
            return entries.Values.SelectMany(we => we).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        public int Count {
            get { return count; }
        }
    }
}
